// ==================================================================================
// Shared Genomics Project MPI Codebase
// Version 1.0 30/04/2010
//
// (c) 2010 University of Manchester all rights reserved
//
// This file is distributed under the GNU General Public License, Version 2.  
// Please see the file COPYING.txt for more details
// ==================================================================================

/*!
\file 
\brief Implementation of Data conversion routines
*/

#include <stdio.h>
#include <stdlib.h>

#include "convert.h"
#include "csnp.h"

// convert an analysis from a SNP-major to a person-major representation.
int snp_to_ind(struct mapfile *map, struct pedfile *ped) {
	int size_of_bool_array, personIndex, snpIndex;

	if (map == NULL || ped == NULL) return -1;
	else if (map->nSNP == 0) return -1;
	else if (ped->nSample == 0) return -1;

	// Allocate the "one/two" space foreach individual.
	size_of_bool_array = sizeof(BOOL) * map->nSNP;
	for (personIndex = 0; personIndex < ped->nSample; personIndex++) {
		ped->sample[personIndex]->one = (BOOL*) malloc(size_of_bool_array);
		ped->sample[personIndex]->two = (BOOL*) malloc(size_of_bool_array);

		if (ped->sample[personIndex]->one == NULL || ped->sample[personIndex]->two == NULL) {
			return 0;
		}
	}

	// Load up the one/two array fro each person.
	for (personIndex = 0; personIndex < ped->nSample; personIndex++) {
		struct individual *person = ped->sample[personIndex];

		for (snpIndex = 0; snpIndex < map->nSNP; snpIndex++) {
			person->one[snpIndex] = map->SNP[snpIndex]->one[personIndex];
			person->two[snpIndex] = map->SNP[snpIndex]->two[personIndex];
		}

		person->nOne = person->nTwo = map->nSNP;
	}
	
	// Free the unused SNP array.
	for (snpIndex = 0; snpIndex < map->nSNP; snpIndex++) {
		csnp_free_attributes(map->SNP[snpIndex]);
		free(map->SNP[snpIndex]);
	}
	free(map->SNP);
	map->SNP = NULL;
	map->nSNP = 0;

	return 1;
}